import * as API from "@/services";
import React, {FC, useCallback, useContext} from "react";
import useAuthedCheck from "@/components/hooks/UseAuthedCheck";
import {HxConfigContext} from "@/layouts/HxConfigContext";
import classNames from "classnames";
import {Image, message} from "antd";
import default_art_cover from "@/assets/default_art_cover.png";
import {correspVal} from "@/utils/biz";
import HxIcon from "@/components/HxIcon";
import "./JournalPeriodItem.less"
import {FormattedMessage} from "umi";

interface JournalPeriodItemProps {
  showTitle?: boolean;
  item: API.FrontJournalPeriod;
  journal?: API.FrontJournal | API.Journal_Summary;
  onClick?: React.MouseEventHandler<HTMLDivElement>;
  onJournalPeriodChange?: (period: API.FrontJournalPeriod) => void;
}


export const JournalPeriodItem: FC<JournalPeriodItemProps> = (props) => {
  const {showTitle = false, journal, item, onClick, onJournalPeriodChange} = props;
  const authedCheck = useAuthedCheck();
  const {isZhCN} = useContext(HxConfigContext)

  const fav = useCallback(() => {
    authedCheck(() => {
      API.fav("period", item!.id, !!item?.hascollection).then(resp => {
        if (resp.flag) {
          message.success(!item?.hascollection ? "收藏成功":"已取消收藏");
          onJournalPeriodChange?.({
            ...item!,
            hascollection: !item?.hascollection,
          })
        }
      })
    })
  }, [item]);

  return (
    <div className={classNames("jp-collapse-item", {"jp-collapse-item-has-title": showTitle})}>
      <div className={"jp-collapse-item-cover"} onClick={onClick}>
        <Image src={item?.journalCoverPath || journal?.journalCoverPathUrl} fallback={default_art_cover} preview={false}/>
      </div>
      <div className={"jp-collapse-item-content"}>
        {
          showTitle && (
            <div className={"jp-collapse-item-tile"}>
              {correspVal(isZhCN, journal?.journalNameCn, journal?.journalNameEn)}
            </div>
          )
        }
        <div className={"jp-collapse-item-name-wrapper"}>
          <div className={"jp-collapse-item-name"} onClick={onClick}>
            <FormattedMessage id="journal.period-info.period-desc" values={{year: item.year, volume: item.volume, period: item.period}}/>
          </div>
          <div className={"jp-collapse-item-fav"}>
            <a onClick={(e) => {
              e.preventDefault();
              fav();
            }}>
              <HxIcon type={!!item?.hascollection ? "hxicon-shoucang-yishoucang" : "hxicon-shoucang"}/>
            </a>
          </div>
        </div>
      </div>
    </div>
  );
};
